﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace amuudp.package
{
    public class Package
    {
        public byte[] Bytes { get; private set; }

        public int Size { get; private set; }

        public int Id { get; private set; }

        private int Num { get; set; }

        private int CurrentNum { get; set; }

        public bool Complete
        {
            get
            {
                return CurrentNum == Num;
            }
        }

        public int Type
        {
            get
            {
                if (!Complete)
                {
                    throw new Exception("数据包接收不完整");
                }
                return UdpCommon.ByteCopyToInt(Bytes, 8);
            }
        }

        public int ClientId
        {
            get
            {
                if (!Complete)
                {
                    throw new Exception("数据包接收不完整");
                }
                return UdpCommon.ByteCopyToInt(Bytes, 0);
            }
        }

        public Package(Fragment firstFragment)
        {
            this.Id = firstFragment.PackageId;
            this.Size = firstFragment.Size;
            this.Num = this.Size / UdpCommon.DataMaxLength + 1;
            this.CurrentNum = 0;
            this.Bytes = new byte[this.Size];

            AddFragment(firstFragment);
        }

        public void AddFragment(Fragment fragment)
        {
            if (fragment.PackageId != Id)
            {
                throw new Exception("包ID不一致");
            }

            fragment.ReadData(Bytes, UdpCommon.DataMaxLength * fragment.Index);
            this.CurrentNum++;
        }
    }

}
